import Component from "../../../../wxsys/lib/base/component";

function request(option) {
    return new Promise(function(resolve, reject) {
        option = option || {};
        option.success = function(res) {
            resolve(res);
        };
        option.fail = function(error) {
            reject(error);
        };
        wx.request(option);
    });
}

export default class WxPay extends Component {
    constructor(page, id, props, context) {
        super(page, id, props, context);
    }

    sendPay() {
        var self = this;
        var options = {};

        //微信小程序支付 
        //options.payType = "miniprogram";
        options.tradeType = "JSAPI";
        var openid = this.props.openid;
        var outTradeno = this.props.outTradeno;
        var totalFee = this.props.totalFee;
        var productId = this.props.productId;
        var productName = this.props.productName;
        var shopName = this.props.shopName;

        // 支付前
        this.fireEvent('payBefore', {
            source: this
        });

        if(openid) {
            options.openid = this.page[this.props.$executeExprBinding_openid](this.context.vars) || this.props.openid;;
        }

        if(outTradeno){
            options.outTradeNo = this.page[this.props.$executeExprBinding_outTradeno](this.context.vars) || this.props.outTradeno;
            if(!options.outTradeNo){
                self.page.hint("订单号不能为空！");
                return;
            }
        } else {
            self.page.hint("请设置订单号");
            return;
        }

        if (totalFee) {
            options.totalFee = this.page[this.props.$executeExprBinding_totalFee](this.context.vars) || this.props.totalFee;
            if(options.totalFee==undefined || options.totalFee.length==0){
                this.page.hint('总金额不能为空！');
                return
            }
            options.totalFee = parseFloat(options.totalFee) * 100;
        } else {
            this.page.hint('请设置总金额！');
            return
        }

        if (shopName) {
            shopName = this.page[this.props.$executeExprBinding_shopName](this.context.vars) || this.props.shopName;
            if(shopName==undefined || shopName.length==0){
                this.page.hint('店铺名称不能为空！');
                return
            }
        } else {
            this.page.hint('请设置店铺名称！');
            return
        }

        if (productName) {
             productName = this.page[this.props.$executeExprBinding_productName](this.context.vars) || this.props.productName;
            if(productName==undefined || productName.length==0){
                this.page.hint('商品名称不能为空！');
                return
            }
        } else {
            this.page.hint('请设置商品名称！');
            return
        }

        // 非必须参数
        if (productId != undefined) {
             options.productId = this.page[this.props.$executeExprBinding_productId](this.context.vars) || this.props.productId;
        }

        if (this.props.limitPay) {
            options.limitPay = this.props.limitPay;
        }

        options.body = shopName + "-" + productName;

        // ide模拟支付处理    
        if(window && window.isDebug){
            wx.requestPayment({
                'timeStamp': '',
                'nonceStr': '',
                'package': '',
                'signType': '',
                'paySign': '',
                'success': function(res) {
                     setTimeout(function(){
                        self.fireEvent('paySuccess', {
                            source: self
                        });
                    },2000)
                },
                'fail': function(res) {
                   setTimeout(function(){
                        self.fireEvent('payFail', {
                            source: self
                        });
                    },2000)
                }
            })
            
            return
        }
        

        request({
            url: wx.App.baseUrl + '/wxapi/miniapp/pay/unifiedOrder',
            method: 'POST',
            data: JSON.stringify(options),
            header: {
                'content-type': 'application/json;charset=UTF-8'
            }
        }).then((res) => {
            var msg = res.data.msg;

            if(msg.indexOf('<err_code_des>')>0){
                msg = msg.split('<err_code_des><![CDATA[')[1].split(']]></err_code_des>')[0]
            }
            if (res.data.success) {
                if (res.data.data != undefined) {
                    var msgData = res.data.data;
                    msgData.prepayId = msgData.packageValue.replace("prepay_id=",'');
                    wx.requestPayment({
                        'timeStamp': res.data.data.timeStamp,
                        'nonceStr': res.data.data.nonceStr,
                        'package': res.data.data.packageValue,
                        'signType': res.data.data.signType,
                        'paySign': res.data.data.paySign,
                        'success': function(res) {
                            self.fireEvent('paySuccess', {
                                source: self,
                                payEvent: msgData
                            });
                        },
                        'fail': function(res) {
                            self.fireEvent('payFail', {
                                source: self,
                                data: res.data
                            });
                        }
                    })
                } else {
                    this.page.hint(msg);
                    self.fireEvent('payFail', {
                        source: self,
                        data: res.data
                    });
                }

            } else {
                this.page.hint(msg);
                self.fireEvent('payFail', {
                    source: self,
                    data: res.data
                });
            }

        })

    }

    initOperation() {
        super.initOperation();

        var operations = {
            'sendPay': {
                label: "支付",
                argsDef: [],
                method: function(args) {
                    return this.owner.sendPay();
                }
            }

        };

        for (let name in operations)
            this.defineOperation(name, operations[name]);
    }

}

wx.comp = wx.comp || {};
wx.comp.WxPay = WxPay;